//AUTHOR:第七页(diqye) 2014年12月7日,  21:31:23 QQ:262666212
(function(root,factory){
	if (typeof define === 'function' && define.amd) {
		define(function(){
			return factory.call(root);
		});
	}else{
		window.TPL=factory.call(root);
	}
}(this,function(){
var config={
			tag:{
				"if":{
						open: function(target){
							return "if("+target+"){";
						},
						close: function(){
							return "}";
						}
				},
				"else":{
					open:function(target){
						if(target==null||config.kit.trim(target)=="")return "}else{"
						return "}else if("+target+"){"
					}
				},
				"each":{
					open:function(target){
						var r1="config.kit.each("+target+",function($item,$index){",
							r2="var $value=$item;",
							r3="with($item){";
						return r1+r2+r3;
					},
					close:function(){
						return "}});"
					}
				},
				"=":{
					open:function(target){
						return "_.push(config.kit.encode("+target+"));"
					}
				},
				"html":{
					open:function(target){
						return "_.push("+target+");"
					}
				}	
			},
			kit:{
				each:function(a,b){
					for(var i=0,l=a.length;i<l;i++) b(a[i],i);
				},
				trim:function(str){
					if(str==null)return"";
					return str.replace(/(^\s*)|(\s*$)/g, "");
				},
				encode: function( text ) {
					return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
				},
				unspace:function( args ) {
					return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
				}
			},
			cache:{}
		};
		function complie(name, tmpl ) {
			if(name in config.cache)return config.cache[name]
			var fnstr="var _=[];data=data||{};"+
				"with(data){_.push('"+
				tmpl.replace( /([\\'])/g, "\\$1" ).replace( /[\r\t\n]/g, " " ).replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
				.replace( /\{\{(\/?)(\w+|.)([^\}]+)?\s*\}\}/g,function(all, slash, type, target){
					var tag=config.tag[type],oc=slash?"close":"open";
					return "');" +
					tag[oc](config.kit.unspace(target))+
					"_.push('";
				})+	
				"');}return _;",fn=new Function("data",fnstr);
			config.cache[name]=fn;
			return fn;
		}
		function tmpl(name,data){
			if(data==null)return config.cache[name]().join("");
			data.config=config;
			return config.cache[name](data).join("");
		}

		return {
			config:config,
			complie:complie,
			tmpl:tmpl
		};
}));

